package com.Jshop.user.service;

import com.Jshop.common.utils.CodecUtils;
import com.Jshop.user.mapper.UserMapper;
import com.Jshop.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;


@Service
public class UserService extends User {

    @Autowired
    private UserMapper userMapper;

    public Boolean checkData(String data, Integer type) {

        User record =  new User();
        switch (type){
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                return null;
        }
        //注册_ 数据库中无值 _ 可用
        return this.userMapper.selectCount(record) == 0 ;

    }

    public User queryUser(String username, String password) {
        //查询
        User recode = new User();
        recode.setUsername(username);
        User user = this.userMapper.selectOne(recode);
        //校验用户名
        if (user == null){
            return null;
        }
        //校验密码
        // MD5(原密码 + 随机串) = DB Password
        if (!user.getPassword().equals(CodecUtils.md5Hex(password,user.getSalt()))){
            return null;
        }
        return user;
    }

    public Boolean addPoint(String userName){
        User user = new User();
        user.setUsername(userName);
        List<User> users = this.userMapper.select(user);
        //用户查询失败
        if (users == null || users.size() != 1){
            return null;
        }
        //此处用户操作是串行的，不必考虑并发问题
        User u = users.get(0);
        //用户积分 + 1
        u.setPoint(u.getPoint() + 1);
        this.userMapper.updateByPrimaryKey(u);
        return Boolean.TRUE;
    }


    /**
     * @Description //用户注册
     * @Param [user]
     * @return java.lang.Boolean
     * @Date  2021/10/22
     **/
    public void register(User user){
        User u = new User();
        //生成随机盐
        String salt = CodecUtils.generateSalt();
        System.out.println(salt);
        //密码加密
        String pass = CodecUtils.md5Hex(user.getPassword(), salt);
        u.setUsername(user.getUsername());
        u.setPassword(pass);
        u.setPhone("12345678");
        u.setSalt(salt);
        u.setCreated(new Date());
        System.out.println(u);
        this.userMapper.insert(u);
    }

    /**
     * @Description //根据用户名查询查询用户
     * @Param [user]
     * @return java.lang.Boolean
     * @Date  2021/10/22
     **/
    public User queryByName(String name){
        User user = new User();
        user.setUsername(name);
        return this.userMapper.selectOne(user);
    }

}
